<script setup lang="ts">
import { onMounted, ref } from 'vue'

// 响应式数据
const regex = ref('')
const testText = ref('')
const testResult = ref('')
const selectedCommon = ref('')
const showAIGenerateModal = ref(false)
const aiDescription = ref('')
const selectedModel = ref('')
const selectedProviderId = ref('')
const availableModels = ref<any[]>([])

// 常用正则表达式
const commonRegex = [
    { label: '邮箱地址', value: '/^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$/' },
    { label: '手机号', value: '/^1[3-9]\\d{9}$/' },
    { label: '身份证号', value: '/^\\d{17}[\\dXx]$/' },
    { label: 'URL', value: '/^https?:\\/\\/[\\w-]+(\\.[\\w-]+)+([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?$/' },
    { label: '日期 (YYYY-MM-DD)', value: '/^\\d{4}-\\d{2}-\\d{2}$/' },
    { label: 'IP地址', value: '/^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$/' }
]

// 组件挂载时初始化
onMounted(async () => {
    // 加载可用模型
    try {
        const models = await (globalThis as any).focusany.llmListModels()
        availableModels.value = models
        if (models.length > 0) {
            selectedModel.value = models[0].modelId
            selectedProviderId.value = models[0].providerId
        }
    } catch (error) {
        console.error('Failed to load models:', error)
    }
})

    ; (globalThis as any).focusany.onPluginReady((data: any) => {
        console.log('onPluginReady', data)
    })

// 测试正则表达式
const testRegex = () => {
    try {
        const pattern = new RegExp(regex.value.replace(/^\/|\/[gimuy]*$/g, ''), 'g')
        const matches = testText.value.match(pattern)
        if (matches) {
            testResult.value = matches.join('\n')
        } else {
            testResult.value = '未匹配到'
        }
    } catch (error) {
        testResult.value = `正则表达式错误: ${error}`
    }
}

// 选择常用表达式
const onCommonSelect = (value: any) => {
    regex.value = value
    selectedCommon.value = ''
}

// 选择模型
const onModelChange = (value: any) => {
    const modelId = value as string
    const model = availableModels.value.find(m => m.modelId === modelId)
    if (model) {
        selectedProviderId.value = model.providerId
    }
}

// AI生成正则表达式
const generateWithAI = async () => {
    if (!aiDescription.value || !selectedModel.value) {
        return
    }

    try {
        const prompt = `请根据以下描述生成一个正则表达式：${aiDescription.value}\n\n请直接返回正则表达式，不要其他说明。`
        const response = await (globalThis as any).focusany.llmChat({
            providerId: selectedProviderId.value,
            modelId: selectedModel.value,
            message: prompt
        })

        if (response && response.data && response.data.message) {
            regex.value = response.data.message.trim()
        }
    } catch (error) {
        console.error('AI生成失败:', error)
    } finally {
        showAIGenerateModal.value = false
        aiDescription.value = ''
    }
}
</script>

<template>
    <div class="min-h-screen bg-gray-50">

        <!-- 主要内容区域 -->
        <main class="max-w-4xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
            <!-- 正则表达式输入框 -->
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">正则表达式</label>
                <a-input v-model="regex" placeholder="输入正则表达式，如 /hello/i" />
            </div>

            <!-- 常用表达式下拉 和 AI生成按钮 -->
            <div class="mb-4 flex space-x-4">
                <div class="flex-1">
                    <a-select v-model="selectedCommon" placeholder="选择常用表达式" @change="onCommonSelect">
                        <a-option v-for="item in commonRegex" :key="item.value" :value="item.value">
                            {{ item.label }}
                        </a-option>
                    </a-select>
                </div>
                <a-button type="primary" @click="showAIGenerateModal = true">AI生成</a-button>
            </div>

            <!-- 测试文本输入框 -->
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">测试文本</label>
                <a-textarea v-model="testText" placeholder="输入待测试的字符串" :rows="4" />
            </div>

            <!-- 测试输出结果 -->
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">测试结果</label>
                <a-textarea v-model="testResult" :rows="4" readonly />
            </div>

            <!-- 测试按钮 -->
            <a-button type="primary" @click="testRegex" class="w-full">测试正则表达式</a-button>
        </main>

        <!-- AI生成弹窗 -->
        <a-modal v-model:visible="showAIGenerateModal" title="AI生成正则表达式" @ok="generateWithAI"
            @cancel="showAIGenerateModal = false">
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">描述</label>
                <a-textarea v-model="aiDescription" placeholder="描述你想要的正则表达式，如：匹配邮箱地址" :rows="3" />
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">选择模型</label>
                <a-select v-model="selectedModel" placeholder="选择AI模型" @change="onModelChange">
                    <a-option v-for="model in availableModels" :key="model.modelId" :value="model.modelId">
                        {{ model.modelName }}
                    </a-option>
                </a-select>
            </div>
        </a-modal>

    </div>
</template>
